package star.cloud.asme.base.file.easyExcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import star.cloud.asme.system.user.excel.UserDTO;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
@RequiredArgsConstructor
public class EasyExcelServiceImpl<T> implements EasyExcelService<T> {


    @Override
    public void exportData(HttpServletResponse response, Class<T> clazz, List<T> list, String fileName) {

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
            response.setCharacterEncoding("utf-8");
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), clazz).sheet("user").doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void importData(MultipartFile file, Class<T> clazz, ReadListener<T> readListener) throws IOException {
        EasyExcel.read(file.getInputStream(), UserDTO.class, readListener).sheet().doRead();
    }

}